/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useRef, useEffect } from 'react'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import styles from './index.module.scss'
import {
  getArticleInfo,
  addArticle,
  editArticle
} from '@/store/actions/article'
import {
  Form,
  Card,
  Breadcrumb,
  Input,
  Radio,
  Button,
  Upload,
  message,
  Space
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { BASEURL } from '@/utils/request'
import { Link, useHistory, useParams } from 'react-router-dom'
import Channel from '@/components/Channel'

import { useDispatch } from 'react-redux'

export default function Publish () {
  const params = useParams()
  console.log('useParams', params)
  const { id } = params
  useEffect(
    () => {
      // 2.发送ajax 拿到数据
      const getInfo = async () => {
        console.log('useEffect', id)
        if (id) {
          const articleInfo = await dispatch(getArticleInfo(id))
          console.log('dispatch----', articleInfo)

          const article = {
            type: articleInfo.cover.type, // 图片类型
            content: articleInfo.content,
            channel_id: articleInfo.channel_id,
            title: articleInfo.title
          }

          // 3. 数据回填
          refForm.current.setFieldsValue(article)
          // 按upload组件的要求对封面进行转换
          setFileList(articleInfo.cover.images.map((img) => ({ url: img }))) // 显示封面图片
        }
      }
      getInfo(id)
    },
    [id]
  )

  const dispatch = useDispatch()
  const history = useHistory()

  const refForm = useRef(null)
  // 在多次渲染之间共享fileList
  const refFileList = useRef([])
  const [fileList, setFileList] = useState([])
  const [type, setType] = useState(1)
  const onChange = (obj) => {
    console.log('图片上传组件', obj) // obj.fileList
    refFileList.current = obj.fileList
    setFileList(obj.fileList)
    // 手动触发表单校验 type字段
    refForm.current.validateFields(['type'])
  }

  // 组装参数
  const buildData = (values) => {
    const cover = {
      type: values.type,
      images: fileList.map((it) => {
        if (it.url) {
          return it.url
        } else {
          return it.response.data.url
        }
      })
    }

    const data = {
      title: values.title,
      content: values.content,
      channel_id: values.channel_id,
      cover
    }
    return data
  }

  // 组装接口需要的数据
  const add = async (values, draft) => {
    const data = buildData(values)
    if (id) {
      // 判断 是添加 还是 修改
      data.id = id
      try {
        await dispatch(editArticle(data, draft))
        message.success(draft ? '修改草稿成功' : '修改文章成功 ', 1, () => {
          // 添加成功以后，路由跳转
          history.push('/home/list')
        })
      } catch (err) {
        message.success('修改失败', 1, () => {})
      }
    } else {
      // 不是编辑
      try {
        await dispatch(addArticle(data, draft))
        message.success(draft ? '存入草稿成功' : '发布文章成功 ', 1, () => {
          // 添加成功以后，路由跳转
          history.push('/home/list')
        })
      } catch (err) {
        message.success('添加失败', 1, () => {})
      }
    }
  }
  // 发布 文章
  const onFinish = async (values) => {
    // console.log(values)
    add(values, false)
  }
  // 添加 草稿
  const addDraft = async () => {
    // 获取表单的values
    const values = await refForm.current.validateFields()
    add(values, true)
  }
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>发布 | 编辑文章</Breadcrumb.Item>
          </Breadcrumb>
        }>
        <Form
          ref={refForm}
          name="basic"
          initialValues={{
            type: 1,
            content: '',
            channel_id: 0,
            title: ''
          }}
          onFinish={onFinish}>
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '标题不能为空'
              }
            ]}>
            <Input placeholder="请输入文章的标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '频道不能为空'
              }
            ]}>
            <Channel />
          </Form.Item>

          <Form.Item
            label="封面"
            name="type"
            rules={[
              {
                validator (_, value) {
                  if (value === fileList.length) {
                    return Promise.resolve()
                  } else {
                    return Promise.reject(new Error('请上传图片'))
                  }
                }
              }
            ]}>
            <Radio.Group
              value={type}
              onChange={(e) => {
                console.log(e.target.value)
                // 更新图像数量
                setType(e.target.value)
                // 更新fileList:从refFileList中取出前type
                setFileList(refFileList.current.slice(0, e.target.value))
              }}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item>
            {/* action: 决定图片上传的接口地址
            name：上传的参数名 */}
            <Upload
              listType="picture-card"
              className="avatar-uploader"
              fileList={fileList}
              onChange={onChange}
              name="image"
              maxCount={type}
              action={`${BASEURL}upload`}>
              {fileList.length < type && <PlusOutlined />}
            </Upload>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '内容不能为空' }]}>
            <ReactQuill />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              发布文章
            </Button>
            <Button onClick={addDraft}>存入草稿</Button>
            <Space />
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
